package com.example.homework

import android.os.Bundle
import android.view.Gravity
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT
import androidx.viewpager.widget.ViewPager
import kotlinx.android.synthetic.main.activity_tab.*

class TabActivity : AppCompatActivity() {
    private var leftView: PercentText? = null
    private var rightView: PercentText? = null
    private var leftPosition: Int = 0
    private var rightPosition: Int = 0
    private var lastSelectedPosition = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_tab)
        val tabAdapter = TabAdapter(supportFragmentManager, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT)
        view_pager.adapter = tabAdapter
        tabLayout.setupWithViewPager(view_pager)

        for ( i in 0 until tabAdapter.count){
            val tabV = PercentText(this)
            tabV.textSize = 16f
            tabV.gravity = Gravity.CENTER
            tabV.text = tabAdapter.getPageTitle(i)
            tabV.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.MATCH_PARENT)
            tabLayout.getTabAt(i)?.customView = tabV
        }

        view_pager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrollStateChanged(state: Int) {
            }

            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {

                leftPosition = Math.min(lastSelectedPosition,position)
                if (leftPosition != tabAdapter.count-1) {
                    rightPosition = leftPosition + 1
                    leftView = tabLayout.getTabAt(leftPosition)?.customView as PercentText?
                    rightView = tabLayout.getTabAt(rightPosition)?.customView as PercentText?
                    leftView?.needChangeRed = false
                    rightView?.needChangeRed = true
                    leftView?.percent = positionOffset
                    rightView?.percent = positionOffset
                }
            }

            override fun onPageSelected(position: Int) {
                lastSelectedPosition = position
            }


        })
    }
}